const CART_LIST = 'cart_list_2022-01-18'

const state = {
    cartLists: uni.getStorageSync(CART_LIST) || []
}
const mutations = {
    SET_CARTLIST(state, data) {
        // console.log(8, state)
        const index = state.cartLists.findIndex(item => data.goods_id === item.goods_id)
        if (index !== -1) {
            // 已存在
            // state.cartLists = state.cartLists.map(item => {
            //     return {...item,nums:item.nums + 1}
            // })
            state.cartLists[index].nums++ 
        } else {
            // 不存在
            state.cartLists.push({...data,nums:1,checked:true})
        }
        // 数据持久化
        uni.setStorageSync(CART_LIST, state.cartLists);  
    },
    EDIT_CARTLIST(state, data) {
        state.cartLists = [...data]
        uni.setStorageSync(CART_LIST, state.cartLists);
    },
    // 修改checked
    EDIT_CHK(state, index) {
        state.cartLists[index].checked = !state.cartLists[index].checked
        uni.setStorageSync(CART_LIST, state.cartLists);
    },
    // 修改数量
    EDIT_NUMS(state, { index, unit }) {
        state.cartLists[index].nums += unit
        uni.setStorageSync(CART_LIST, state.cartLists);
    },
    // 删除
    DEL_CARTLIST(state,index) {
        state.cartLists.splice(index,1)
        uni.setStorageSync(CART_LIST, state.cartLists);
    },
    CHECKED_ALL(state, checked) {
        state.cartLists.forEach(item => item.checked = checked)
        uni.setStorageSync(CART_LIST, state.cartLists);
    }
}
const actions = {}

export default {
    namespaced: true,
    state,
    mutations,
    actions
}